# coding=utf-8
"""
@project : TestDemo
@author  : huyi
@file   : app.py
@ide    : PyCharm
@time   : 2021-10-15 11:58:44
"""
from flask import Flask, request
from gevent.pywsgi import WSGIServer
from gevent import monkey
import json
 
# 将python标准的io方法，都替换成gevent中的同名方法，遇到io阻塞gevent自动进行协程切换
monkey.patch_all()
 
app = Flask(__name__)

class DataRegister():
    def __init__(self):
        self.adcValue = 0

    def PutData(self, data):
        self.adcValue = data

    def GetData(self):
        return self.adcValue

class CmdRegister():
    def __init__(self):
        self.reqList = []
        self.resList = []

    # 传输协议格式
    class TramsmitPaket:
        def __init__(self, head, len, cmd, subCmd, data):
            self.head = head     # head发送时使用"key":int 的方式发送整形
            self.len = len       # len发送时使用"key":int 的方式发送整形
            self.cmd = cmd       # cmd发送时使用"key":int 的方式发送整形
            self.subCmd = subCmd # subCmd发送时使用"key":int 的方式发送整形
            self.data = data     # data发送时使用"key":[] 的方式发送列表
            self.checkSum = 0    # checkSum发送时使用"key":int 的方式发送整形
            self.state = 0       # state发送时使用"key":int 的方式发送整形

    def GetReqList(self):
        if self.reqList :
            return self.reqList.pop()
        else:
            return None

    def AddReq(self, obj):
        self.reqList.append(obj)

    def GetResList(self):
        if self.resList:
            return self.resList.pop()
        else:
            return None

    def AddRes(self, obj):
        self.resList.append(obj)

    def PopRes(self, id):
        for obj in self.resList:
            if obj.head == id:
                tmp = obj
                self.resList.remove(obj)
                return tmp
        return None

class HttpObj():
    # app = Flask(__name__)
    def __init__(self, cmdObj, dataObj):
        self.dataHan = dataObj
        self.cmdHan = cmdObj
        # self.server = WSGIServer(('192.168.10.100', 8000), app).serve_forever()

cmdhan = CmdRegister()
dataHan = DataRegister()
myHttp = HttpObj(cmdhan, dataHan)

def GetHttpHan():
    return myHttp

# 客户端直接传{'key':'value'}的值
@app.route('/data', methods=['POST', 'GET'])
def data():
    han = GetHttpHan()
    if request.method == 'GET':
        resData = "adc:" + str(han.dataHan.GetData())
        # print(resData)
        return resData
    else:
        print(request.data)
        request_data = json.loads(request.data)
        adcData = request_data.get('adc')
        print("adcData", adcData, type(adcData))
        han.dataHan.PutData(adcData)
        return "ok"

#将接收到的json用loads函数拆解
@app.route('/cmdRegister', methods=['GET', 'POST']) 
def cmdRegister():
    han = GetHttpHan()
    if request.method == 'GET':
        req = han.cmdHan.GetReqList()
        # print("req", type(req))
        if req!= None:
            return json.dumps(
            req,
            default=lambda obj: obj.__dict__,
            sort_keys=True,
            indent=4)
        else:
            return "noreq"            
    else:
        request_data = json.loads(request.data)
        head = request_data.get('head')
        len = request_data.get('len')
        cmd = request_data.get('cmd')
        subCmd = request_data.get('subCmd')
        data = request_data.get('data')
        obj = CmdRegister.TramsmitPaket(head, len, cmd, subCmd, data)
        han.cmdHan.AddReq(obj)
        return "ok"


# 客户端需要传{'key':'value'}的值，这里传指令head
@app.route('/resRegister', methods=['GET', 'POST'])
def resRegister():
    han = GetHttpHan()
    if request.method == 'GET':
        request_data = json.loads(request.data)
        head = request_data.get('head')
        # print("head", type(head), head)
        res = han.cmdHan.PopRes(head)
        if res!= None:
            return json.dumps(
            res,
            default=lambda obj: obj.__dict__,
            sort_keys=True,
            indent=4)
        else:
            return "nores"
    else:
        request_data = json.loads(request.data)
        head = request_data.get('head')
        len = request_data.get('len')
        cmd = request_data.get('cmd')
        subCmd = request_data.get('subCmd')
        data = request_data.get('data')
        obj = CmdRegister.TramsmitPaket(head, len, cmd, subCmd, data)
        # print(type(obj), obj)  
        han.cmdHan.AddRes(obj)
        return "ok"

if __name__ == '__main__':
    print("遇事不决，可问春风。")
    WSGIServer(('192.168.10.100', 8000), app).serve_forever()
    # cmdhan = CmdRegister()
    # dataHan = DataRegister()
    # myHttp = HttpObj(cmdhan, dataHan)